<script setup lang="ts">
import { ref, onActivated } from 'vue'
import { useStorage } from '@/hooks/web/useStorage'
import { useRouter } from 'vue-router'
import { editPassword } from '@/api/user'
import { useAppStore } from '@/store/modules/app'
import { showFailToast } from 'vant'

const appStore = useAppStore()
const userInfo = ref(appStore.getUserInfo)
const { clear } = useStorage()
const { push, back } = useRouter()
const password = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
onActivated(() => {
  userInfo.value = appStore.getUserInfo
})
const onSubmit = (values: any) => {
  editPassword({
    userId: userInfo.value.id,
    ...values
  }).then((res) => {
    if (res.success) {
      clear()
      push({
        name: 'login'
      })
    } else {
      showFailToast(res.message)
    }
  })
}

const onBack = () => {
  back()
}
const isEqual = () => confirmPassword.value == newPassword.value
</script>

<template>
  <van-nav-bar title="修改密码" fixed placeholder left-arrow @click-left="onBack"> </van-nav-bar>
  <div class="wrapper">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="旧密码"
          :rules="[{ required: true, message: '请输入旧密码' }]"
        />
        <van-field
          v-model="newPassword"
          name="newPassword"
          type="password"
          label="新密码"
          :rules="[{ required: true, message: '请输入新密码' }]"
        />
        <van-field
          v-model="confirmPassword"
          name="confirmPassword"
          label="确认密码"
          type="password"
          :rules="[
            { required: true, message: '请再次输入新密码' },
            { validator: isEqual, message: '两次输入的密码不一致' }
          ]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 修改密码 </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="less" scoped>
.wrapper {
  padding: 16px 0;
}
.btnBox {
  padding: 32px 16px;
}
</style>
